package com.zhia.demo.controller;


import com.zhia.demo.entity.UserEntity;
import com.zhia.demo.service.UserService;
import com.zhia.demo.vo.ResultVo;
import com.zhia.demo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author DONG
 * @create 2023/10/24 21:04
 */

@RestController
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/user/{uname}")
    private ResultVo checkUser(@PathVariable("uname") String uname) {
        ResultVo resultVo = new ResultVo();
        if (!userService.checkUser(uname)) {
            resultVo.setCode(1L);
            resultVo.setMessage("账号已存在");
        }
        return resultVo;

    }

    @PostMapping("/user")
    private String reg(UserEntity user) {
        userService.addUser(user);
        return "注册成功，前去登录吧";
    }

    @GetMapping("/user/login")
    private ResultVo login(String username, String password, HttpServletResponse response) {
        UserEntity user = userService.getUser(username, password);
        ResultVo resultVo = new ResultVo();
        if (user != null) {
            if(user.getPwd() != null) {
                Cookie cookie = new Cookie("USERSESSION", user.getId().toString());
                cookie.setPath("/");
                cookie.setMaxAge(2 * 24 * 60 * 60);
                response.addCookie(cookie);
                resultVo.setData(user);
            }else {
                resultVo.setCode(1L);
                resultVo.setMessage("密码错误");
            }
        }else {
            resultVo.setCode(1L);
            resultVo.setMessage("没有该账号，前去注册吧");
        }
        return resultVo;
    }

    @GetMapping("/user")
    private ResultVo getUserByCookie(@CookieValue(name = "USERSESSION", defaultValue = "") String cookie) {
        ResultVo resultVo = new ResultVo();
        if(!StringUtils.isEmpty(cookie))  {
            UserEntity user = userService.getById(Integer.parseInt(cookie));
            UserVo userVo = new UserVo(user.getId(),user.getNickname());
            resultVo.setData(userVo);
        }else {
            resultVo.setCode(1L);
        }
        return resultVo;
    }
    @GetMapping("/username/{id}")
    public ResultVo getUsernameById(@PathVariable("id") Integer id) {
        UserEntity user = userService.getById(id);
        ResultVo resultVo = new ResultVo();
        if(user != null) {
            resultVo.setData(user.getNickname());
        }else {
            resultVo.setCode(1L);
        }
        return resultVo;
    }

    @GetMapping("/user/logout")
    private void logout(HttpServletResponse response) {
        Cookie cookie = new Cookie("USERSESSION", null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);}
}
